<!-- 字典下拉选择 -->
<template>
    <div class="dic_select">
        <el-select v-model="selectedValue" :multiple="multiple" :placeholder="`请选择${label}`"
            @change="select" clearable style="width: 100%;" :disabled="disabled">
            <el-option v-for="item in dicOptions" :key="item[dicValueType]"
                 :label="item.dictLabel" :value="item[dicValueType]" />
        </el-select>
    </div>
</template>
<script setup>
    import { ref, watch, onMounted } from "vue"
    import { listDataV2 } from "@/api/system/dict/data";
    const props = defineProps([ 'label', 'value', 'dicName', 'multiple', 'valueType', 'disabled' ]);
    const emit = defineEmits([ 'update:value', 'select' ]);
    const selectedValue = ref(null);
    const dicOptions = ref([]);
    const dicValueType = ref(props.valueType || 'dictCode')
    watch(() => props.value, () => {
        selectedValue.value = props.value;
    }, { deep: true, immediate: true });
    const select = (id) => {
        const options = [];
        if(props.multiple){
            id.map( item => {
                dicOptions.value.map(cItem => {
                    if(cItem[dicValueType.value] == item){
                        options.push(cItem);
                    }
                });
            })
        }else{
            dicOptions.value.map(cItem => {
                if(cItem[dicValueType.value] == id){
                    options.push(cItem);
                }
            });
        }
        selectedValue.value = id;
        emit('update:value', id);
        emit('select', id, options);
    };
    const getDicOptions = () => {
        listDataV2({
            dictType: props.dicName || ''
        }).then((res) => {
            dicOptions.value = res.data ? res.data : [];
        });
    };
    onMounted(()=>{
        getDicOptions();
    });
</script>
<style lang="scss" scoped>
    .dic_select{
        width: 100%;
    }
</style>